package com.javer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.javer.dao.support.DataSourceDaoSupport;
import com.javer.dao.support.ResultUtils;
import com.javer.domain.Article;
import com.javer.domain.PageView;

@Repository
public class ArticleDao extends DataSourceDaoSupport {
	private RowMapper mapper = new ArticleMapper();
	
	public PageView getPageByType(PageView pv, String type) {
		String sql1 = "select count(*) from article where atype="+type;
		String sql2 = "select c.*,(select count(*) from comment where ctype=1 and tid=c.id) commentcount from article c where c.atype="+type+" order by id desc";
		return getByPage(pv, sql1, sql2);
	}
	
	public List<Article> getNewArticle(int atype, int limit) {
		if (limit <=0 ) {
			limit = 300;
		}
		return jdbcTemplate.query("select * from article where atype="+ atype +" order by id desc limit " + limit, mapper);
	}
	
	public void addArticle(Article article) {
		Assert.notNull(article, "article must not be null");
		String sql = "insert into article(title,content,comefrom,author,atime,atype) values(?,?,?,?,now(),?)";
		Object[] args = new Object[]{article.getTitle(), article.getContent(), article.getComefrom(), article.getAuthor(), article.getAtype()};
		jdbcTemplate.update(sql, args);
	}
	
	public void updateArticle(Article article) {
		Assert.notNull(article, "article must not be null");
		String sql = "update article set title=?,content=?,comefrom=?,author=?,atype=? where id=?";
		Object[] args = new Object[]{article.getTitle(), article.getContent(), article.getComefrom(), article.getAuthor(), article.getAtype(), article.getId()};
		jdbcTemplate.update(sql, args);
	}
	
	public PageView getByPage(PageView pv) {
		String sql1 = "select count(*) from article";
		String sql2 = "select c.*,(select count(*) from comment where ctype=1 and tid=c.id) commentcount from article c order by id desc";
		return super.getByPage(pv, sql1, sql2);
	}
	
	public Article getById(int id) {
		return (Article) jdbcTemplate.queryForObject("select * from article where id=" + id, mapper);
	}
	
	@Override
	protected RowMapper getMapper() {
		return mapper;
	}

	static class ArticleMapper implements RowMapper {

		public Object mapRow(ResultSet rs, int i) throws SQLException {
			Article a = new Article();
			a.setId(rs.getInt("id"));
			a.setTitle(rs.getString("title"));
			a.setContent(rs.getString("content"));
			a.setAuthor(rs.getString("author"));
			a.setComefrom(rs.getString("comefrom"));
			a.setAtime(rs.getTimestamp("atime"));
			a.setAtype(rs.getString("atype"));
		    a.setCommentCount(ResultUtils.getInt(rs, "commentcount"));
			return a;
		}
		
	}
}
